package com.atguigu.tingshu.user.strategy.impl;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Author  王东剑
 * Created on 24/6/2024 下午8:00
 * Package_name com.atguigu.tingshu.user.strategy.impl
 * Description 声音购买保存交易信息的策略
 */
@Slf4j
@Service
public class UserPaidTrackStrategyImpl implements UpdateUserPaidRecordStrategy {
	@Autowired
	private UserPaidTrackService userPaidTrackService;
	@Autowired
	private TrackInfoFeignClient trackInfoFeignClient;
	@Override
	public void updateUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {
		List<Long> itemIdList = userPaidRecordVo.getItemIdList();
		String orderNo = userPaidRecordVo.getOrderNo();
		Long userId = userPaidRecordVo.getUserId();
		TrackInfo trackInfo = trackInfoFeignClient.getTrackInfo(itemIdList.get(0)).getData();
		// 防止重复消费
		long count = userPaidTrackService.count(new LambdaQueryWrapper<UserPaidTrack>()
				.eq(UserPaidTrack::getAlbumId, trackInfo.getAlbumId())
				.eq(UserPaidTrack::getUserId,userId)
				.in(UserPaidTrack::getTrackId,itemIdList));
		if(count>=itemIdList.size()) return;
		// 声音购买保存交易信息的策略
		Long albumId = trackInfo.getAlbumId();
		List<UserPaidTrack> userPaidTrackList = itemIdList.stream().map(itemId -> {
			UserPaidTrack userPaidTrack = new UserPaidTrack();
			userPaidTrack.setOrderNo(orderNo);
			userPaidTrack.setUserId(userId);
			userPaidTrack.setAlbumId(albumId);
			userPaidTrack.setTrackId(itemId);
			return userPaidTrack;
		}).collect(Collectors.toList());
		userPaidTrackService.saveBatch(userPaidTrackList);
	}

	@Override
	public String getItemType() {
		return SystemConstant.ORDER_ITEM_TYPE_TRACK;
	}
}
